<?php
$zTemplate->set_file ( 'main', '../templates/zhsearch.html' );
$KeywordOrig = $_REQUEST['txtSearch'];


$a=ereg('['.chr(0xa1).'-'.chr(0xff).']', $KeywordOrig);

$a= ($a && strlen($KeywordOrig) > 3) || (!$a && strlen($KeywordOrig) > 2)  ? 1 :0; 
if(!$a && $KeywordOrig)
{
	//exit('zoule');
	header('location:../googlesearch.html?q='.urlencode(iconv('gbk','utf-8',$KeywordOrig)));	
}
elseif(!$a && !$KeywordOrig)
{
	header('location:../index.html');	
}


//echo $a,$KeywordOrig;

$db = phpclone($dbObj);
//$sql = "SELECT temp_userid FROM `org_firststep` where org_name like '%".$KeywordOrig."%' and `acc_status`<>10";

if ($_SESSION['myCityChoice'] <> 9)
{
	$sql = "SELECT temp_userid FROM `org_firststep` where org_name like '%".$KeywordOrig."%' and  `city_id`=" . $_SESSION['myCityChoice']. "  and `acc_status`<>10";
}
else
{
	$sql = "SELECT temp_userid FROM `org_firststep` where org_name like '%".$KeywordOrig."%' and `acc_status`<>10";
}


$iNumberOfId = $db -> getQueryNum($sql); 
if($iNumberOfId==0)
{
	header('location:../googlesearch.html?q='.urlencode(iconv('gbk','utf-8',$KeywordOrig)));	
}
//echo $KeywordOrig;
$beginTime = microtime(true);
require_once('ctword.php');
$newarr = array();
$newarr = keyword_pscw($KeywordOrig);
$langPackage = array('sMerchantType','sHighClick','sFollow','sKeyword','sSearchResult','sSort','sCity','sDefault','sBrowseTimes','sCommentTimes','sClickTimes',
						'sType','sBrowse','sCommentTimes','sFans','sSearchResults','sSearchResultDanWei','sTel');
//print_r($newarr);

$zTemplate->set_var('KeywordOrigutf',urlencode(iconv('gbk','utf-8',$KeywordOrig)));
$zTemplate->set_var('KeywordOriggbk',urlencode($KeywordOrig));
$zTemplate->set_var('KeywordOrig',$KeywordOrig);

$query = NULL;
$i = 0;
$query = array();
foreach ($newarr as $k => $v)
{
	$query[$i] = $v[1];
	$i += 1;	
}
//print_r($query);
if ($KeywordOrig == "")
{
	$zTemplate->set_var ( array ('GlobalTitle' => $MStr['sSearch'].' -- '.$MStr['globalslogan'] ));
}
else
{
	$zTemplate->set_var ( array ('GlobalTitle' => $MStr['sSearch'].': '. $KeywordOrig . ' -- '.$MStr['globalslogan'] ));
}							 



$isLoginUser = 'Y';
// IDENTIFY IF IT IS A LOGON USER
if(!isset($aususrpinverid) || !isset($aususrtype))
{
	$isLoginUser = 'N';
}
/*
;if more than 50 records, just show 50 items.
*/
$cquery=array();
$querycondition='';
if(count($query)>0)
{
	foreach($query as $item)
	{
		if(mb_strlen($item,'gbk')>=2)
		{
			$cquery[]=$item;
		}
	}	
}
count($query)<1 ? '' :$query=$cquery;  
if(count($query)>0)
{
	foreach($query as $item)
	{
		if($_SESSION['myCityChoice'] <> 9)
		{
			$querycondition.=" or org_name like '%$item%' and  `city_id`=" . $_SESSION['myCityChoice']. " and `acc_status`<>10";
		}
		else
		{
			$querycondition.=" or org_name like '%$item%'  and `acc_status`<>10";
		}
	}
}
count($query)>=1&&!in_array($KeywordOrig,$query) ? $query[]=$KeywordOrig : '';
/*get the page*/
$zPage = ((! isset ( $page )) or ($page <= 0)) ? 1 : $page;
$offset = ($zPage - 1) * $rowCount;


if($_SESSION['myCityChoice'] <> 9)
{
	$sql = "SELECT temp_userid FROM `org_firststep` where org_name like '%".$KeywordOrig."%' and  `city_id`=" . $_SESSION['myCityChoice']. " and `acc_status`<>10";
}
else
{
	$sql = "SELECT temp_userid FROM `org_firststep` where org_name like '%".$KeywordOrig."%' and `acc_status`<>10";
}


$querycondition && $sql.=$querycondition. ' order by case when org_name like \'%'.$KeywordOrig.'%\' then 0 else 1 end ';

//echo $sql;
$iNumberOfId = $db -> getQueryNum($sql); 



$sql .= " LIMIT 5";
$ContentId = $db -> executeQuery($sql);
$iNumberOfId1=count($ContentId);
$zTemplate->set_block ( 'main', 'merList', 'Msglist' );

//print_r($query);
for($i=0; $i<$iNumberOfId1; $i++)
{
			$UsrId = $ContentId[$i][0];
			/*
			Search commercial and official database
			*/
			$sql = "SELECT * FROM `org_firststep`  where temp_userid='".$UsrId."' and `acc_status`<>10";
			$tR = $db -> getOneQuery($sql);
			if($tR)
			{
				$sql = "SELECT a.usr_id,a.curr_addr,a.self_intro,a.city_id,a.sort_id, a.hits, a.usr_phone,IFNULL(b.total,0) as total, IFNULL(c.fansTotal,0) as fansTotal FROM ((`org_details` a LEFT JOIN (SELECT COUNT(*) AS total, `obj_usr_id` FROM `cs_comments` GROUP BY `obj_usr_id`) b ON a.usr_id=b.obj_usr_id)) LEFT JOIN (SELECT COUNT(*) AS fansTotal, `fds_id` FROM `usr_relationship` GROUP BY `fds_id`) c  ON a.usr_id = c.fds_id  WHERE `temp_userid` = '".$UsrId."'";

				$val = $db -> getOneQuery($sql);
				//print_r($val);
				$imgFace = getUserFace($val['usr_id']);
				if($val['hits']=='') $val['hits'] = 0;
				if($val['total'] == '') $val['total'] = 0;
				$tel = Cvt2Red($query, $tR['tel']);
				$org_name = $query ? Cvt2Red($query, $tR['org_name']):$tR['org_name'];
				
				$sLink = $webAddress."/viewinfo/".$UsrId."/";
				
				if($isLoginUser == 'N')
				{
					$langPackage[] = 'sFollower';
					$zTemplate -> set_var('btnFocusId','focusBtn');
				}
				else
				{
					$sql = "SELECT 1 FROM `usr_relationship` WHERE `usr_id` = '".getUsrRealId($aususrpinverid,$aususrtype)."' AND `fds_id` = '".$val['usr_id']. "'";
					$rs = $db -> getOneQuery($sql);
					if($rs)
					{
						$zTemplate -> set_var(array('btnFocusId'=>'focusBtnAlready','sFollower'=>$MStr['sFollowed'],'defocus'=>'Y'));
					}
					else 
					{
						$zTemplate -> set_var(array('btnFocusId'=>'focusBtn','sFollower'=>$MStr['sFollower'],'defocus'=>'N'));
					}
				}
				$zTemplate -> set_var(array(
				'usrFace'=>$imgFace,
				'NickName'=>$org_name,
				'BusAddress'=>$curr_addr,
				'hitNum'=>$val['hits'],
				'commNum'=>$val['total'],
				'tel' => $tel,
				'cityName'=>getCityName($val['city_id'], $language),
				'despBus'=>$desp,
				'BusType'=>getSortName($val['sort_id'], $language),
				'busTel'=>$val['usr_phone'],
				'busLink'=>$webAddress.'/viewinfo/'.$tR['temp_userid'].'/',
				'businId'=>$val['usr_id'],
				'fansNum'=>empty($val['fansTotal']) ? 0 : $val['fansTotal'],
				));
				$zTemplate->parse ( 'Msglist', 'merList', true );
				$pageDone = new pageNaviDone ( $zPage, $prevPage, $nextPage, $totalPages,  empty($KeywordOrig) ? 1 : '1-'.urlencode($KeywordOrig));
				$tBody = $pageDone -> printGooglePageNav();
				$zTemplate->set_var('extraArea',$tBody);
			}

}


if($Content == '')
{
	$Content = $MStr['sNoSearchResult'];
}

/*
Preparing left side as classification
*/
$db2 = phpclone($dbObj);

$zTemplate->set_block ( 'main', 'optMenu', 'Menu' );

$sql = "SELECT * FROM `cs_sort` WHERE `bMain` = '1' ORDER BY `ID` DESC"; 
$result = $db2 -> executeQuery($sql);
$i = 0;
if($result)
{
	$queryStr = 'btnQuery='.base64_encode("Y").'&sortName=';
	foreach($result as $val)
	{
		if($val['Sort_ID'] == 0) continue;
	
		if ($language == 2)
		{
			$zTemplate->set_var ( array ('sortList'=>$val['Sort_Name'],'sortImg'=>$val['img'],'totalNum'=>$num['total'],'QueryString'=>$queryStr.$val['Sort_ID']));
		}
		else
		{
			$zTemplate->set_var ( array ('sortList'=>$val['str_eng'],'sortImg'=>$val['img'],'totalNum'=>$num['total'],'QueryString'=>$queryStr.$val['Sort_ID']));
		}
		$zTemplate->parse ( 'Menu', 'optMenu', true );
	}
}
$endTime = microtime(true);

$totalTime = round(($endTime - $beginTime),4);

/*
Bug fixed by Liang Fan on 18/2/2012
Here is sharing a public module which was moved to Shared/merchant_rank.php
*/
include_once("./../Shared/merchant_rank.php");

$zTemplate -> set_var(array(
'Content' => $Content, 
'ServiceSort'=>$ServiceSort,
'QueryShow'=>$MStr['sTotalGot'] .$iNumberOfId . $MStr['sSearchTmp'] .$totalTime. $MStr['sSecond'],
'Business'=>$MStr['sType'],
'City'=>$MStr['sCity'],
'Address' => $MStr['sAddress'],
'Details' => $MStr['sDetails'],
'CheckDetails' => $MStr['sCheckDetails'],
'Type' => $MStr['sType'],

));


$currentPage = '';